//
//  DateExtension.swift
//  SwiftDemo1
//
//  Created by wzp on 2025/6/22.
//

import Foundation

extension Date {
    static func createDateString(createAtStr: String) -> String {
        let fmt = DateFormatter()
        fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        fmt.locale = Locale(identifier: "en")
        
        guard let createDate = fmt.date(from: createAtStr) else {
            return ""
        }
        
        let nowDate = Date()
        let interval = Int(nowDate.timeIntervalSince(createDate))
        
        if interval < 60 {
            return "刚刚"
        }
        
        if interval < 60*60 {
            return "\(interval / 60)分钟前"
        }
        
        if interval < 60 * 60 * 24 {
            return "\(interval / (60*60))小时前"
        }
        
        let calendar = NSCalendar.current
        
        if calendar.isDateInYesterday(createDate) {
            fmt.dateFormat = "昨天 HH:mm"
            let timeStr = fmt.string(from: createDate)
            return timeStr
        }
        
        let components = calendar.dateComponents([.year], from: createDate, to: nowDate)
        
        if let year = components.year, year < 1 {
            fmt.dateFormat = "MM-dd HH:mm"
            let timeStr = fmt.string(from: createDate)
            return timeStr
        }
        
        fmt.dateFormat = "yyyy-MM-dd HH:mm"
        return fmt.string(from: createDate)
    }
}
